<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Device;
use App\Model\Site;
use App\Model\User;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    public function postSiteDevice(Request $request)
    {
        $site_id = $request->input('site_id');
        $devices = Device::getDevicesBySiteId($site_id);
        return $this->json_success($devices);
    }

    public function getCreateSiteDevice(Request $request)
    {
        $site_id = $request->input('site_id');
        $site = Site::with('groups')->find($site_id);
        $user = User::find($site->user_id);

        return view('admin.device.create-site-device', [
            'site' => $site,
            'user' => $user
        ]);
    }

    public function postCreateSiteDevice(Request $request)
    {
        $params = $request->all();
        $site_id = $request->input('site_id');
        $site = Site::find($site_id);
        if (!$site) {
            return $this->json_error('电站不存在', 1001);
        }
        $params['user_id'] = $site->user_id;
        $device = Device::create($params);
        if ($device) {
            return $this->json_success($device);
        } else {
            return $this->json_sys_error();
        }
    }

    public function getEditSiteDevice(Request $request)
    {
        $site_id = $request->input('site_id');
        $id = $request->input('id');
        $site = Site::with('groups')->find($site_id);
        $user = User::find($site->user_id);
        $device = Device::find($id);

        return view('admin.device.edit-site-device', [
            'site' => $site,
            'user' => $user,
            'device' => $device
        ]);
    }

    public function postEditSiteDevice(Request $request)
    {
        $params = $request->all();
        $id = $request->input('id');
        $device = Device::find($id);
        if (!$device) {
            return $this->json_error('设备不存在', 1001);
        }
        $device = $device->update($params);
        return $this->json_success($device);
    }

    public function postDeleteDevice(Request $request)
    {
        $id = $request->input('id');
        $device = Device::find($id);
        if (!$device) {
            return $this->json_error('设备不存在！', 1001);
        }
        $device->delete();
        return $this->json_success();
    }

}
